package com.fpx.order.plat.bussiness.service.order.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fpx.order.plat.bussiness.dao.log.IOrderSynclogDao;
import com.fpx.order.plat.bussiness.dao.order.IOriginOrderAddressDao;
import com.fpx.order.plat.bussiness.dao.order.IOriginOrderDao;
import com.fpx.order.plat.bussiness.dao.order.IOriginOrderitemDao;
import com.fpx.order.plat.bussiness.entity.OrderSynclog;
import com.fpx.order.plat.bussiness.entity.OrderSynclogFail;
import com.fpx.order.plat.bussiness.entity.OriginOrder;
import com.fpx.order.plat.bussiness.entity.OriginOrderitem;
import com.fpx.order.plat.bussiness.service.order.IOriginOrderService;
import com.fpx.order.plat.bussiness.system.PlatConstants;
import com.fpx.order.plat.web.utils.PageUtil;

/**
 * 
 * desc: 订单信息Service实现类
 * @author xiangtao(xiangtao@4px.com)
 * @date 2015年12月3日 下午4:58:10
 * @version 1.0
 */
@Service("originOrderService")
public class OriginOrderServiceImpl implements IOriginOrderService{
	
	public final Logger LOGGER=Logger.getLogger(OriginOrderServiceImpl.class);
	
	@Autowired
	private IOriginOrderDao originOrderDao;
	
	@Autowired
	private IOriginOrderitemDao originOrderitemDao;
	
	@Autowired
	private IOriginOrderAddressDao orderAddressDao;
	
	@Autowired
	private IOrderSynclogDao orderSynclogDao;
	
	@Override
	public void save(OriginOrder originOrder) throws Exception {
		//订单号
		String orderId = originOrder.getOrder_code();
		//订单渠道
		String orderSource = originOrder.getPlatform_code();
		//判断原始订单是否存在
		OriginOrder oriorder = findOriOrderByOrderCd(orderId,orderSource);
		
		//判断OMS订单是否存在
		OriginOrder order = findOrderByOrderCd(orderId,orderSource);
		
		if(oriorder != null){
			throw new RuntimeException(orderId+" 订单 在原始订单表已存在！不保存");
		}else if(order!=null){
			throw new RuntimeException(orderId+" 订单 在OMS订单表已存在！不保存");
		}
		/**
		 * 保存订单时 需要保存两份 原始订单表一份，OMS订单表一份 
		 */
		//保存到原始订单表
		int oriExecRow = originOrderDao.saveOriginoOrder(originOrder);
		if(oriExecRow<=0){
			throw new RuntimeException("【"+orderId+"】订单 保存到原始订单时失败");
		}
		//取原始订单表序列生成的主键
		int oriPfooId=originOrder.getPfoo_id();
		//保存到OMS使用的订单表
		int execRow=originOrderDao.saveOrder(originOrder);
		if(execRow<=0){
			throw new RuntimeException("【"+orderId+"】订单 保存到OMS订单时失败");
		}
		//取OMS订单表序列生成的主键
		int pfoId=originOrder.getPfoo_id();

		//设置关联主键ID
		originOrder.getOrderAddress().setFk_pfoo_id(oriPfooId);
		//保存原始订单地址信息
		execRow=orderAddressDao.saveOriginOrderAddress(originOrder.getOrderAddress());
		if(execRow<=0){
			throw new RuntimeException("【"+orderId+"】订单 保存到原始订单地址信息时失败");
		}
		//设置关联主键ID
		originOrder.getOrderAddress().setFk_pfoo_id(pfoId);
		//保存oms订单地址信息
		execRow=orderAddressDao.saveOrderAddress(originOrder.getOrderAddress());
		if(execRow<=0){
			throw new RuntimeException("【"+orderId+"】订单 保存到OMS订单地址信息时失败");
		}
		for(OriginOrderitem orderitem:originOrder.getOrderitems()){
			orderitem.setFk_pfoo_id(oriPfooId);
			int flag1 = originOrderitemDao.saveOriOrderitem(orderitem);
			orderitem.setFk_pfoo_id(pfoId);
			int fiag2= originOrderitemDao.saveOrderitem(orderitem);
			if(flag1<=0){
				throw new RuntimeException("【"+orderId+"】,保存原始订单货品信息失败");
			}else if(fiag2<=0){
				throw new RuntimeException("【"+orderId+"】,保存OMS订单货品信息失败");
			}
		 }
	}
	
	
	/**
	 * <p>Title: findByOrderCode</p>
	 * <p>Desc: 查询OMS订单信息</p>
	 * @author xiangtao(xiangtao@4px.com)
	 * @date 2015年12月3日 下午5:49:30 
	 * @version 1.0
	 * @param order_code
	 * @param plat_code
	 * @return
	 * @throws Exception
	 */
	public OriginOrder findOrderByOrderCd(String order_code,String plat_code) throws Exception{
		//查询条件
		OriginOrder queryCondition = new OriginOrder();
		//参考单号
		queryCondition.setOrder_code(order_code);
		queryCondition.setPlatform_code(plat_code);
		//查询
		List<OriginOrder> orderLists = originOrderDao.findOrder(queryCondition);
		if(orderLists==null||orderLists.size()<=0){
			return null;
		}
		return orderLists.get(0);
	}
	
	/**
	 * <p>Title: findByOrderCode</p>
	 * <p>Desc: 查询原始订单信息</p>
	 * @author xiangtao(xiangtao@4px.com)
	 * @date 2015年12月3日 下午5:49:30 
	 * @version 1.0
	 * @param order_code
	 * @param plat_code
	 * @return
	 * @throws Exception
	 */
	public OriginOrder findOriOrderByOrderCd(String order_code,String plat_code) throws Exception{
		//查询条件
		OriginOrder queryCondition = new OriginOrder();
		//参考单号
		queryCondition.setOrder_code(order_code);
		queryCondition.setPlatform_code(plat_code);
		//查询
		List<OriginOrder> orderLists = originOrderDao.findOriginOrder(queryCondition);
		if(orderLists==null||orderLists.size()<=0){
			return null;
		}
		return orderLists.get(0);
	}


	@Override
	public List<OriginOrder> findDeliveryOrder(String cm_id, String cs_code,
			String plat_code) throws Exception{
		//查询条件
		OriginOrder queryCondition = new OriginOrder();
		queryCondition.setCustomer_id(cm_id);//客户ID
		queryCondition.setShop_account(cs_code);//店铺代码
		queryCondition.setPlatform_code(plat_code);
		queryCondition.setPfo_os_code(PlatConstants.ORDER_STATUS_COMPLETE);//已处理
		queryCondition.setUpload_ship_code(PlatConstants.UPLOAD_STATUS_N);//未上传
		return originOrderDao.findDeliveryOrder(queryCondition);
	}


	@Override
	public void updateDeliveryStatusSuccess(List<String> orderCodes,
			String plat_code) throws Exception {
		if(orderCodes==null||orderCodes.size()<=0||plat_code==null){
			throw new Exception("参数异常");
		}
		String upload_status=PlatConstants.UPLOAD_STATUS_Y;
		int execRow=originOrderDao.updateDeliveryStatus(
				orderCodes,upload_status, plat_code);
		if(execRow<=0){
			throw new Exception("更新订单成功状态 时失败");
		}
	}


	@Override
	public void updateDeliveryStatusfailure(String order_code,
			String plat_code, String failureMessage) throws Exception {
		if(order_code==null||order_code.length()<=0||plat_code==null){
			throw new Exception("参数异常");
		}
		List<String> orderCodes=new ArrayList<String>();
		orderCodes.add(order_code);
		String upload_status=PlatConstants.UPLOAD_STATUS_U;
		int execRow=originOrderDao.updateDeliveryStatus(
				orderCodes, upload_status, plat_code);
		if(execRow<=0){
			throw new Exception("更新订单失败状态 时失败");
		}
		OrderSynclog orderSynclog=new OrderSynclog();
		orderSynclog.setRef_code(order_code);
		orderSynclog.setOp_id("");
		orderSynclog.setZn_content("OPS同步运单号失败");
		orderSynclog.setEn_content("Synchronization waybill number failed");
		int exEsg=orderSynclogDao.saveSynclog(orderSynclog);
		if(exEsg<=0){
			throw new Exception("添加订单同步失败日志时失败");
		}
		OrderSynclogFail synclogFail=new OrderSynclogFail();
		synclogFail.setPf_al_id(orderSynclog.getPf_al_id());
		synclogFail.setError_msg(failureMessage);
		exEsg=orderSynclogDao.saveSynclogFial(synclogFail);
		if(exEsg<=0){
			throw new Exception("添加订单同步失败异常日志时失败");
		}
	}


	@Override
	public Map<String, Object> findPageOrder(Map<String, Object> map)
			throws Exception {
			if(map==null){
				throw new Exception("分页请求参数不能为空");
			}
			try{
				if(!StringUtils.isNumeric((String)map.get("page"))||
						!StringUtils.isNumeric((String)map.get("rows"))){
					throw new Exception("分页参数page,rows只能为数字");
				}
			}catch(Exception e){
				throw new Exception("分页请求参数不正确");
			}
			//当前页
			int page=Integer.parseInt((String)map.get("page"));
			//每页行数
			int rows=Integer.parseInt((String)map.get("rows"));
			//开始查询的行数
			int start_no=PageUtil.getStartNo(page, rows);
			map.put("start_no", String.valueOf(start_no));
			//结束查询的行数
			int end_no=PageUtil.getEndNo(rows, start_no);
			map.put("end_no", String.valueOf(end_no));
			//根据条件分页查询数据
			List<OriginOrder>originOrderLst=originOrderDao.findPageOriginOrder(map);
			//根据条件查询总行数
			int records=originOrderDao.findCountOriginOrder(map);
			map.put("rows", originOrderLst);//变成数据集了
			map.put("records", records);//总行数
			map.put("total",PageUtil.getPageSize(records, rows));//总页数
			return map;
	}

}

